package cn.alex.sso.client.demo.util;

import cn.alex.sso.client.demo.config.LscConfig;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Alex
 * @date 2025/1/10 下午1:23
 */
public class LscUtil {

    /**
     * 校验ticker是否合法
     *
     * @param ticket ticket
     * @return 当前Ticket的用户ID
     */
    public static String checkTicket(String ticket) {
        Map body = RequestUtil.requestPost(LscConfig.CHECK_TICKET_URL, new TreeMap<String, Object>() {{
            put("ticket", ticket);
            put("ssoLogoutCall", LscConfig.LOGOUT_CALL_URL);
        }});

        Integer code = MapUtil.getInt(body, "code");
        String data = MapUtil.getStr(body, "data");

        if (code != 200 || StrUtil.isBlank(data)) {
            return null;
        }

        return data;
    }

    /**
     * 单点退出
     *
     * @param loginId 用户ID
     */
    public static void ssoLogout(String loginId) {
        RequestUtil.requestPost(LscConfig.LOGOUT_URL, new TreeMap<String, Object>() {{
            put("loginId", loginId);
        }});
    }

    /**
     * 解密
     *
     * @param content 待解密内容
     */
    public static String decrypt(String content) {
        byte[] key = LscConfig.APP_SECRET_KEY.getBytes(StandardCharsets.UTF_8);
        byte[] aesKey = new byte[16];
        System.arraycopy(key, 0, aesKey, 0, 16);

        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, aesKey);

        return aes.decryptStr(content);
    }
}
